package com.xx.linkage.handler;

import cn.hutool.core.util.StrUtil;
import com.xx.domain.entity.DisposeLog;
import com.xx.netty.server.AisServer;
import com.xx.util.AisCommandUtil;
import com.xx.web.domain.dto.EnvDto;
import com.xx.web.domain.entity.DisposeRule;
import com.xx.web.proto.ShipOuterClass;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AisHandler extends AbstractDisposeHandler {
    protected boolean test(DisposeRule disposeRule) {
        return disposeRule.getAis();
    }

    protected void accept(DisposeRule disposeRule, ShipOuterClass.Ship ship, EnvDto envDto, DisposeLog disposeLog) {
        // 开启 ais报文
        if (disposeRule.getAis() && StringUtils.isNotBlank(disposeRule.getAisContent())) {
            log.info("开始发送ais报文");
            if (AisServer.clientChannel != null) {
                ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
                //String abm = "$--ABM,1,1,2,{},3,6,{},{}*{}\r\n";
                //"$--ABM,1,1,2,123123123,3,6,Il69raDNqRAcgQrpNJ1Sv:O:J<Srp6gr:,0*1E\r\n"
                String content = StrUtil.format(disposeRule.getAisContent(),
                        StringUtils.isNotBlank(ship.getChineseName()) ? ship.getChineseName() : ship.getName());
                disposeLog.setAisContent(content);
                disposeLog.setSave(true);
                List<String> list = AisCommandUtil.xToY_send(ship.getMmsi(), "ABM", "", content);
                if (AisServer.clientChannel.isActive()) {
                    for (String command : list) {
                        buffer.clear();
                        ByteBuf byteBuf = buffer.writeBytes(command.getBytes());
                        AisServer.clientChannel.writeAndFlush(byteBuf).addListener(
                                (ChannelFutureListener) future -> {
                                    if (future.isSuccess()) {
                                        // 发送成功
                                        log.info("ais报文: {} has been sent successfully.", command);
                                    } else {
                                        // 发送失败
                                        log.error("Failed to send {}: {}", command, future.cause());
                                    }
                                });
                    }
                } else {
                    // 通道已关闭，处理相应逻辑
                    log.error("发送ais报文失败,通道已关闭");
                }

            }
        }
    }
}
